package com.pimee.common.util.net;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pimee.common.util.StringUtils;
import com.pimee.common.util.net.HttpUtil.HttpReturn;
import com.pimee.common.util.net.HttpUtil.Params;

/**
 * 获取地址类
 * 
 * @author Bruce Shaw 2020年2月3日 下午5:18:19
 *
 */
public class AddressUtils {
	private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

	public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo2.php";

	public static String getRealAddressByIP(String ip) {
		String address = "XX XX";

		// 内网不查询
		if (IpUtils.internalIp(ip)) {
			return "内网IP";
		}else {
			Params params = Params.create().add("ip", ip);
			HttpReturn httpReturn = new HttpUtil().post(IP_URL, params);
			if (StringUtils.isEmpty(httpReturn.getRetValue())) {
				log.error("获取地理位置异常 {}", ip);
				return address;
			}
			JSONObject obj;
			try {
				obj = JSON.parseObject(httpReturn.getRetValue());
				JSONObject data = obj.getJSONObject("data");
				String region = data.getString("region");
				String city = data.getString("city");
				address = region + " " + city;
			} catch (Exception e) {
				log.error("获取地理位置异常 {}", ip);
			}
		}
		return address;
	}
	
	public static void main(String[] args) {
		String address = AddressUtils.getRealAddressByIP("113.67.10.93");
		System.out.println(address);
	}
}
